package com.ysucode.controller.user.advice;

import com.ysucode.annotation.MyLogger;
import com.ysucode.constant.Login;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义登录失败的行为
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    //AuthenticationException里封装了用户登陆失败的错误信息
    @Override
    @MyLogger(value = "用户登录", flag = false)
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException e)
            throws IOException, ServletException {

        response.setContentType("text/html;charset=utf-8");
//        response.getWriter().write("<script>alert('登录失败:用户名或密码错误');history.back();</script>");
//        response.getWriter().write(String.valueOf(new Result(false, Login.LOG_ERROR)));
        log.debug(Login.LOG_ERROR);
        response.getWriter().write(Login.LOG_ERROR);
    }
}